package com.huawei.admins.platform.gateway.core.component.limiter;

import com.huawei.admins.platform.gateway.core.component.router.Router;
import com.huawei.admins.platform.gateway.core.util.ServerWebExchangeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class UrlPathKeyResolver implements KeyResolver {

    private static final Logger logger = LoggerFactory.getLogger(UrlPathKeyResolver.class);

    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {

        String uriPath = exchange.getRequest().getURI().getPath();
        Router route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        if (route == null) {
            return Mono.just(uriPath);
        }
        String routeId = route.getId();
        String relativePath = uriPath.replace(routeId, "");

        if (logger.isDebugEnabled()) {
            logger.debug("FInd limited url '{}' on route '{}'", relativePath, routeId);
        }
        return Mono.just(relativePath);
    }
}
